<template>
  <div class="courses-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索课程名称/代码"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-select
              v-model="majorFilter"
              placeholder="专业筛选"
              clearable
              @change="handleSearch"
              style="width: 150px"
            >
              <el-option
                v-for="major in majors"
                :key="major.id"
                :label="major.majorName"
                :value="major.id"
              />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            v-if="userStore.isAdmin"
          >
            新增课程
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="courses"
        border
        style="width: 100%"
      >
        <el-table-column prop="courseCode" label="课程代码" width="120" />
        <el-table-column prop="courseName" label="课程名称" />
        <el-table-column prop="courseType" label="课程类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.courseType === '必修' ? 'success' : 'warning'">
              {{ row.courseType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="userStore.isAdmin"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="userStore.isAdmin"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 课程表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增课程' : '编辑课程'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="课程代码" prop="courseCode">
          <el-input v-model="form.courseCode" :disabled="dialogType === 'edit'" />
        </el-form-item>
        
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" />
        </el-form-item>
        
        <el-form-item label="课程类型" prop="courseType">
          <el-select
            v-model="form.courseType"
            placeholder="请选择课程类型"
            style="width: 100%"
          >
            <el-option label="必修" value="必修" />
            <el-option label="选修" value="选修" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学分" prop="credit">
          <el-input-number
            v-model="form.credit"
            :min="0"
            :max="20"
            :precision="1"
            :step="0.5"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="所属专业" prop="majorId">
          <el-select
            v-model="form.majorId"
            placeholder="请选择专业"
            style="width: 100%"
          >
            <el-option
              v-for="major in majors"
              :key="major.id"
              :label="major.majorName"
              :value="major.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const searchQuery = ref('')
const majorFilter = ref('')
const courses = ref([])
const majors = ref([])

const form = reactive({
  id: null,
  courseCode: '',
  courseName: '',
  courseType: '',
  credit: 0,
  majorId: null
})

const rules = {
  courseCode: [
    { required: true, message: '请输入课程代码', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '课程代码只能包含大写字母和数字', trigger: 'blur' }
  ],
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  courseType: [
    { required: true, message: '请选择课程类型', trigger: 'change' }
  ],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' }
  ],
  majorId: [
    { required: true, message: '请选择所属专业', trigger: 'change' }
  ]
}

const fetchCourses = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/courses', {
      params: {
        majorId: majorFilter.value
      }
    })
    courses.value = res.data
  } catch (error) {
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchMajors = async () => {
  try {
    const res = await request.get('/api/majors')
    majors.value = res.data
  } catch (error) {
    console.error('获取专业列表失败:', error)
  }
}

const handleSearch = () => {
  // 由于后端没有提供搜索接口，这里在前端进行过滤
  if (!searchQuery.value) {
    fetchCourses()
    return
  }
  
  const query = searchQuery.value.toLowerCase()
  courses.value = courses.value.filter(course => 
    course.courseCode.toLowerCase().includes(query) ||
    course.courseName.toLowerCase().includes(query)
  )
}

const resetSearch = () => {
  searchQuery.value = ''
  majorFilter.value = ''
  fetchCourses()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    courseCode: '',
    courseName: '',
    courseType: '',
    credit: 0,
    majorId: null
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    courseCode: row.courseCode,
    courseName: row.courseName,
    courseType: row.courseType,
    credit: row.credit,
    majorId: row.majorId
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`/api/courses/${row.id}`)
    ElMessage.success('删除成功')
    fetchCourses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (dialogType.value === 'add') {
      await request.post('/api/courses', form)
      ElMessage.success('新增成功')
    } else {
      await request.put(`/api/courses/${form.id}`, form)
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    fetchCourses()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

onMounted(async () => {
  await Promise.all([
    fetchCourses(),
    fetchMajors()
  ])
})
</script>

<style scoped>
.courses-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
}
</style> 